package com.buka.service.Impl;

import com.buka.service.CartService;
import com.buka.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.buka.cart.pojo.Cart;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private TokenDecode tokenDecode;

    @Override
    public void add(Cart cart) {
        //获取用户名
        String userName = tokenDecode.getUserInfo().get("user_name");
        //查询购物车
        Cart cart1=(Cart) redisTemplate.boundHashOps("Cart"+userName).get(cart.getProductId());
        if(cart1 == null){
            redisTemplate.boundHashOps("Cart"+userName).put(cart.getProductId(),cart);
        }else {
            //原数量要增加
            cart1.setNum(cart.getNum()+cart1.getNum()/*新增+以前的*/);//数量
            cart1.setMoney(cart.getUnitPrice().multiply(BigDecimal.valueOf(cart1.getNum())));//总价格
            //更新完放回去
            redisTemplate.boundHashOps("Cart"+userName).put(cart1.getProductId(),cart1);

        }
    }

    @Override
    public void delete(String ids) {
        //String[] split = ids.split(",");
        //获取用户名
        String userName = tokenDecode.getUserInfo().get("user_name");

        for (String id: ids.split(",")){
            redisTemplate.boundHashOps("Cart"+userName).delete(Long.valueOf(id));
        }
    }

    @Override
    public List findAll() {
        //获取用户名
        String userName = tokenDecode.getUserInfo().get("user_name");

        List values = redisTemplate.boundHashOps("Cart" + userName).values();

        return values;

    }

    @Override
    public void update(Cart cart) {
        String userName = tokenDecode.getUserInfo().get("user_name");
        redisTemplate.boundHashOps("Cart" + userName).put(cart.getProductId(),cart);
    }
}
